<template>
  <div>
    <NvForm :nv-data="createNvData()" @define-event="handleEvent($event)">
    </NvForm>
  </div>
</template>

<script>
import { onBeforeMount, ref, provide } from 'vue'
import NvForm from './NvForm'
import NvData from '../../js/NvData'
import nvsDataUtils from '../../js/NvsDataUtils'
import ConstDef from '../../js/ConstDef'

export default {
  name: 'NvCursiveForm',
  components: {
    NvForm
  },
  props: {
    nvsData: {
      default: null,
      type: Object
    }
  },
  setup(props) {
    const currentNvId = ref();
    onBeforeMount(() => {
      if (props.nvsData && props.nvsData.nvs.length > 0) { currentNvId.value = props.nvsData.nvs[0].id } else currentNvId.value = -1;
    })

    function createNvData () {
      const currentNvs = nvsDataUtils.searchNvsById(currentNvId.value, props.nvsData.nvs, props.nvsData.nd);
      if (!currentNvs) {
        if (currentNvId.value <= 0) {
          currentNvId.value = props.nvsData.nvs[0].id;
          const currentNvs = nvsDataUtils.searchNvsById(currentNvId.value, props.nvsData.nvs, props.nvsData.nd);
          if (!currentNvs) return null;
        }
      }
      let currentNv = null;
      for (const tempNv of currentNvs) {
        if (tempNv.id === currentNvId.value) {
          currentNv = tempNv;
          break;
        }
      }
      const result = new NvData(currentNvs, currentNv, props.nvsData.nd, props.nvsData.layout);
      return result;
    }

    function getCurrentNv () {
      if (currentNvId.value === -1) return null;
      const result = nvsDataUtils.searchNvById(currentNvId.value, props.nvsData.nvs, props.nvsData.nd);
      return result;
    }
    const cursiveData = ref({
      nvsData: props.nvsData, currentNvId: currentNvId
    });
    provide("cursiveData", cursiveData);
    return {
      currentNvId,
      createNvData,
      getCurrentNv,
      cursiveData
    }
  },
  methods: {
    getParentLayout() {
      let parent = this.$parent();
      while (parent != null) {
        if (parent.isNvLayout) { return parent; } else { parent = parent.$parent; }
      }
      return null;
    },
    getDataSource() {
      return this.getParentLayout().getDataSource();
    },
    handleEvent(event) {
      const functionCode = event.fvData.fdLayout.functionCode;
      if (functionCode === ConstDef.FUNCTION_CODE_CURSIVE_TREE_CHANGE) {
        this.doCursiveForm(event);
      } else {
        this.$emit("define-event", event)
      }
    },
    doCursiveForm(event) {
      // if (this.currentNvId !== event.value) {
      //   this.currentNvId = event.value;
      // }
    }
  }
}
</script>

<style scoped>

</style>
